package com.cgwx.common.utils;

import com.alibaba.fastjson.JSONArray;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.springframework.stereotype.Component;

import java.sql.*;
import java.util.List;

/**
 * @ClassName ListToStringHandler
 * @Description mybatis list转换为String 相互转换工具类
 * @Version V1.0
 */
@Component
public class ListToStringHandler extends BaseTypeHandler<List> {

    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, List list, JdbcType jdbcType) throws SQLException {
        if(list.size() == 0)
        {
            preparedStatement.setNull(i, Types.VARCHAR);
            return;
        }
        String listStr = list.get(0).toString();
        for(int num = 1 ; num < list.size() ; num ++)
        {
            listStr += "," + list.get(num).toString();
        }
        preparedStatement.setString(i, listStr);
    }

    @Override
    public List getNullableResult(ResultSet resultSet, String s) throws SQLException {
        JSONArray jsonArray = JSONArray.parseArray( resultSet.getString(s));
        return jsonArray;
    }

    @Override
    public List getNullableResult(ResultSet resultSet, int i) throws SQLException {
        JSONArray jsonArray = JSONArray.parseArray( resultSet.getString(i));
        return jsonArray;
    }

    @Override
    public List getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        JSONArray jsonArray = JSONArray.parseArray( callableStatement.getString(i));
        return jsonArray;
    }
}
